package com.example.big_orange2.service;

import cn.hutool.http.HttpUtil;
import com.example.big_orange2.entity.WeChatSession;
import com.example.big_orange2.utils.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WeChatService {


    @Value("${weixin.userappid}")
    private String userAppId;

    @Value("${weixin.usersecret}")
    private String userSecret;

    @Value("${weixin.staffappid}")
    private String staffAppId;

    @Value("${weixin.staffsecret}")
    private String staffSecret;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ObjectMapper objectMapper;

    public List<String> get3rdSession(String code, String type) throws Exception {

        WeChatSession ws=getOpenID(code,type);
        String token= UUID.randomUUID().toString().replace("-", "");

        redisUtils.set(token,ws,2, TimeUnit.HOURS);
        List<String> list = new ArrayList<>();
        list.add(ws.getOpenid());
        list.add(token);

        return list;
    }



    public void bindCodeAndToken(String code, String token, String type) throws Exception {

        WeChatSession ws=getOpenID(code,type);
        redisUtils.set(token,ws,2, TimeUnit.HOURS);

    }

    private WeChatSession getOpenID(String code, String type) throws Exception {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = "";
        if(type == "1"){
            replaceUrl = url.replace("{0}", userAppId).replace("{1}", userSecret).replace("{2}", code);
        }else if(type == "2"){
            replaceUrl = url.replace("{0}", staffAppId).replace("{1}", staffSecret).replace("{2}", code);
        }
        System.out.println(replaceUrl);
        String res = HttpUtil.get(replaceUrl);
        System.out.println(res);
        WeChatSession ws=objectMapper.readValue(res, WeChatSession.class);

        if(ws.getOpenid()==null){
            throw new Exception("code 不正确");
        }
        return  ws;
    }


    public Boolean hasLogin(String token) throws WriterException, IOException {
        if(redisUtils.hasKey(token)){

            return true;
        }else{

            return false;
        }
    }
}
